/*
 * Player.cpp
 *
 *  Created on: 21-08-2012
 *      Author: szymon
 */

#include "Player.h"
#include <cassert>
#include "SurfaceOps.h"

Player::Player(Screen * screen)
{
	//Initialize movement variables
	offSet = 0;
	velocity = 0;

	//Initialize animation variables
	frame = 0;
	status = PLAYER_RIGHT;

	//Load the sprite sheet
	playerSurface = SurfaceOps::loadImage("megaman.png");
	assert(playerSurface != NULL);

	setClips();

	this->screen = screen;
}

Player::~Player()
{
	SDL_FreeSurface(playerSurface);
}

void Player::setClips()
{
	for (int i = 0; i < SPRITES_NUM; i++)
	{
		//Clip the sprites
		clipsRight[i].x = 0 + PLAYER_WIDTH * i;
		clipsRight[i].y = 0;
		clipsRight[i].w = PLAYER_WIDTH;
		clipsRight[i].h = PLAYER_HEIGHT;
	}

	for (int i = 0; i < SPRITES_NUM; i++)
	{
		//Clip the sprites
		clipsLeft[SPRITES_NUM - 1 - i].x = 0 + PLAYER_WIDTH * i;
		clipsLeft[SPRITES_NUM - 1 - i].y = PLAYER_HEIGHT;
		clipsLeft[SPRITES_NUM - 1 - i].w = PLAYER_WIDTH;
		clipsLeft[SPRITES_NUM - 1 - i].h = PLAYER_HEIGHT;
	}
}

void Player::handleEvents(SDL_Event * event)
{
	//If a key was pressed
	if (event->type == SDL_KEYDOWN)
	{
		//Set the velocity
		switch (event->key.keysym.sym)
		{
		case SDLK_RIGHT:
			velocity += PLAYER_WIDTH / 8;
			break;
		case SDLK_LEFT:
			velocity -= PLAYER_WIDTH / 8;
			break;
		default:
			break;
		}
	}
	//If a key was released
	else if (event->type == SDL_KEYUP)
	{
		//Set the velocity
		switch (event->key.keysym.sym)
		{
		case SDLK_RIGHT:
			velocity -= PLAYER_WIDTH / 8;
			break;
		case SDLK_LEFT:
			velocity += PLAYER_WIDTH / 8;
			break;
		default:
			break;
		}
	}
}

void Player::move()
{
	//Move
	offSet += velocity;

	//Keep the stick figure in bounds
	if ((offSet < 0) || (offSet + PLAYER_WIDTH > SCREEN_WIDTH))
	{
		offSet -= velocity;
	}
}

void Player::show()
{
	//If Foo is moving left
	if (velocity < 0)
	{
		//Set the animation to left
		status = PLAYER_LEFT;

		//Move to the next frame in the animation
		frame++;
	}
	//If Foo is moving right
	else if (velocity > 0)
	{
		//Set the animation to right
		status = PLAYER_RIGHT;

		//Move to the next frame in the animation
		frame++;
	}
	//If Foo standing
	else
	{
		//Restart the animation
		frame = 0;
	}

	//Loop the animation
	if (frame >= SPRITES_NUM)
	{
		frame = 2;
	}

	//Show the stick figure
	if (status == PLAYER_RIGHT)
	{
		SurfaceOps::applySurface(offSet,
				SCREEN_HEIGHT - PLAYER_HEIGHT - PLAYER_Y_OFFSET, playerSurface,
				screen->surface(), &clipsRight[frame]);
	}
	else if (status == PLAYER_LEFT)
	{
		SurfaceOps::applySurface(offSet,
				SCREEN_HEIGHT - PLAYER_HEIGHT - PLAYER_Y_OFFSET, playerSurface,
				screen->surface(), &clipsLeft[frame]);
	}
}

